package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * @Author:Simple
 * @Date: 2025/8/18 16:13
 * @Description:
 **/
@RestController
@RequestMapping("admin/product")
public class FileUploadController {
    @Value("${minio.endpointUrl}")
    String endpointUrl;
    @Value("${minio.accessKey}")
    String accessKey;
    @Value("${minio.secreKey}")
    String secretKey;
    @Value("${minio.bucketName}")
    String bucketName;

    @PostMapping("fileUpload")
    public Result<String> fileUpload(MultipartFile file) throws Exception {
        String url="";
        MinioClient minioClient = MinioClient.builder().endpoint(endpointUrl).credentials(accessKey, secretKey).build();
        //验证桶是否存在
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if(exists){
            System.out.println("bucket already exists");
        }else {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
        //生成一个不会重复的文件名
        String fileName=System.currentTimeMillis()+ UUID.randomUUID().toString();
        //上传
        minioClient.putObject(PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .stream(file.getInputStream(),file.getSize(),-1)
                        .contentType(file.getContentType())
                        .build());
        url=endpointUrl+"/"+bucketName+"/"+fileName;
        System.out.println("url:\t"+url);
        return Result.ok(url);
    }
}
